package com.wing.product.controller.admin;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wing.cabinet.utils.ExcelUtils;
import com.wing.common.utils.JsonResult;
import com.wing.order.service.DynamicService;
import com.wing.platform.feign.PlatformClient;
import com.wing.product.model.entity.Product;
import com.wing.product.model.entity.ProductCategory;
import com.wing.product.model.entity.ProductDetail;
import com.wing.product.model.request.ProductDto;
import com.wing.product.model.response.ProductVO;
import com.wing.product.service.*;
import com.wing.productself.model.entity.*;
import com.wing.productself.service.ProductBrandSelfService;
import com.wing.productself.service.ProductCategorySelfService;
import com.wing.productself.service.ProductTypeSelfService;
import com.wing.productself.service.ProductUnitSelfService;
import com.wing.web.excel.CompactProductExcelIn;
import com.wing.web.excel.DownExcelUtil;
import com.wing.web.excel.ExcelUtil;
import com.wing.web.excel.ProductExcelIn;
import com.wing.web.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 *
 * @author
 */
@Validated
@Api(value = "Admin-产品明细表管理", tags = "#/product/cabProduct")
@RestController("productController")
@RequestMapping("productCab/admin/product")
@RequiredArgsConstructor
@Slf4j
public class ProductController {

    private final ProductDetailService productDetailService;

    private final ProductService productService;

    private final PlatformClient platformClient;

    @Autowired
    private ProductBrandService productBrandService;

    @Autowired
    private ProductCategoryService productCategoryService;
    @Autowired
    private ProductCategoryExtService productCategoryExtService;
    @Autowired
    private ProductTypeService productTypeService;
    @Autowired
    private ProductUnitService productUnitService;
    @Autowired
    private DynamicService dynamicService;

    @Autowired
    private ProductBrandSelfService productBrandSelfService;
    @Autowired
    private ProductCategorySelfService productCategorySelfService;
    @Autowired
    private ProductTypeSelfService productTypeSelfService;
    @Autowired
    private ProductUnitSelfService productUnitSelfService;

    @Autowired
    private MostUsedKnifeListService mostUsedKnifeListService;

    /**
     * 下载产品数据录入excel模板
     */
    @ApiOperation(value = "下载产品数据录入excel模板")
    @GetMapping("/template")
    public void template(HttpServletResponse response, HttpServletRequest request) throws IOException {
        //String[] headerArr = {"物料名称(*)","产品编码(*)","物料类型(*)","物料分类(*)","关键词","卖点描述","计价方式","单位","品牌","SKU名称(*)","SKU编码(*)","SKU规格编码","渠道价","市场价(*)","平台供货价","最低活动价","商品货号","商品条型码","旧SKU编码","旧SKU规格编码(*)"};
        String[] headerArr = {"物料名称(*)","产品编码(*)","物料分类(*)","物料类型(*)","品牌","SKU名称(*)","SKU编码(*)","SKU规格编码","旧SKU编码","旧SKU规格编码(*)","单位","计价方式","渠道价","平台供货价","市场价(*)","最低活动价","卖点描述","关键词","商品货号","商品条型码"};
        List<String[]> downData = new ArrayList<>();
        //产品类型
        StringBuffer tempStr = new StringBuffer();
        QueryWrapper<ProductTypeSelf> productTypeSelfQueryQrapper = new QueryWrapper<ProductTypeSelf>();
        productTypeSelfQueryQrapper.eq("type", ProductSelf.Type.knife);
        productTypeSelfQueryQrapper.eq("data_source_type", ProductTypeSelf.DataSourceType.enterprise);
        List<ProductTypeSelf> productTypeSelfList = productTypeSelfService.list(productTypeSelfQueryQrapper);
        for (ProductTypeSelf productTypeSelf : productTypeSelfList) {
            tempStr.append(productTypeSelf.getName()).append(",");
        }
        tempStr.delete(tempStr.length()-1, tempStr.length());
        downData.add(tempStr.toString().split(","));
        tempStr.delete(0,tempStr.length());

        //产品分类
        QueryWrapper<ProductCategorySelf> productCategorySelfQueryQrapper = new QueryWrapper<ProductCategorySelf>();
        productCategorySelfQueryQrapper.eq("type", ProductSelf.Type.knife);
        productCategorySelfQueryQrapper.eq("data_source_type", ProductCategorySelf.DataSourceType.enterprise);
        List<ProductCategorySelf> productCategorySelfList = productCategorySelfService.list(productCategorySelfQueryQrapper);
        for (ProductCategorySelf productCategorySelf : productCategorySelfList) {
            tempStr.append(productCategorySelf.getName()).append(",");
        }
        tempStr.delete(tempStr.length()-1, tempStr.length());
        downData.add(tempStr.toString().split(","));
        tempStr.delete(0,tempStr.length());

        //计价方式
        for (ProductSelf.PricingMethod pricingMethod : ProductSelf.PricingMethod.values()) {
            tempStr.append(pricingMethod.getDesc()).append(",");
        }
        tempStr.delete(tempStr.length()-1, tempStr.length());
        downData.add(tempStr.toString().split(","));
        tempStr.delete(0,tempStr.length());

        //单位
        QueryWrapper<ProductUnitSelf> productUnitInfoQueryQrapper = new QueryWrapper<ProductUnitSelf>();
        productUnitInfoQueryQrapper.eq("type", ProductSelf.Type.knife);
        productUnitInfoQueryQrapper.eq("data_source_type", ProductUnitSelf.DataSourceType.enterprise);
        List<ProductUnitSelf> productUnitInfoList = productUnitSelfService.list(productUnitInfoQueryQrapper);
        List<String> newList = productUnitInfoList.stream().map(ProductUnitSelf::getName).distinct().collect(Collectors.toList());
        for (String name : newList) {
            tempStr.append(name).append(",");
        }
        tempStr.delete(tempStr.length()-1, tempStr.length());
        downData.add(tempStr.toString().split(","));
        tempStr.delete(0,tempStr.length());

        //品牌
        QueryWrapper<ProductBrandSelf> productBrandSelfQueryQrapper = new QueryWrapper<ProductBrandSelf>();
        productBrandSelfQueryQrapper.eq("type", ProductSelf.Type.knife);
        productBrandSelfQueryQrapper.eq("data_source_type", ProductBrandSelf.DataSourceType.enterprise);
        List<ProductBrandSelf> productBrandSelfList = productBrandSelfService.list(productBrandSelfQueryQrapper);
        for (ProductBrandSelf productBrandSelf : productBrandSelfList) {
            tempStr.append(productBrandSelf.getName()).append(",");
        }
        tempStr.delete(tempStr.length()-1, tempStr.length());
        downData.add(tempStr.toString().split(","));
        tempStr.delete(0,tempStr.length());

        //String[] indexArr = {"2","3","6","7","8"};
        String[] indexArr = {"3","2","11","10","4"};
        DownExcelUtil.createExcelTemplate(response, request, "产品导入模板", Arrays.asList(headerArr), downData, Arrays.asList(indexArr));
    }


    /**
     * 导入excel
     */
    @ApiOperation(value = "导入excel")
    @PostMapping("/importExcel")
    public JsonResult importExcel(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return JsonResult.fail("上传文件为空！");
        }
        try {
            //获取原始的文件名
            String originalFilename = file.getOriginalFilename();
            String fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length());
            ExcelUtil<ProductExcelIn> reader = new ExcelUtil<>();
            InputStream is = file.getInputStream();
            List<ProductExcelIn> list = reader.read(is,ProductExcelIn.class);
            //List<Product> productList = new ArrayList<>();
            Map<String, Product> productMap = new HashMap<String, Product>();
            if (CollectionUtils.isEmpty(list)) {
                return JsonResult.fail("请在表格中添加数据！");
            }
            List<Product> productList = new ArrayList<Product>();
            for (String key : productMap.keySet()){
                productList.add(productMap.get(key));
            }

            productService.batchAddProduct(productList);
            return JsonResult.success("导入成功！");
        } catch (Exception e) {
            //e.printStackTrace();
            log.error("上传文件异常！异常信息:", e);
            return JsonResult.exception("上传文件异常！异常信息:" + e.getMessage());
        }

    }
    @ApiOperation(value = "产品导出")
    @GetMapping("/export")
    public void export(HttpServletResponse response, String enterpriseCode,String startCreateTime, String endCreateTime){
        List<ProductDto> productDtoList = new ArrayList<>();
        Map paramsMap = new HashMap();
        paramsMap.put("startCreateTime",startCreateTime);
        paramsMap.put("endCreateTime",endCreateTime);
//        paramsMap.put("type",0);
        paramsMap.put("categoryType", ProductCategory.CategoryType.purchase.getValue());

        productDtoList = productService.findAllProduct(paramsMap);
        for (ProductDto item : productDtoList){
            Integer sum=0;
            if(item.getQuantityCellCab()!=null){
                sum+=item.getQuantityCellCab();
            }
            if (item.getQuantityTempCab()!=null){
                sum+=item.getQuantityTempCab();
            }
            item.setQuantityCab(sum);
        }
        ExcelUtils.export(response,"物料列表",productDtoList, ProductDto.class);
    }

    /*@GetMapping(value = "/export", produces = "application/octet-stream")
    @ApiOperation(value = "产品导出")
    public void excel(HttpServletResponse response,String startCreateTime, String endCreateTime) {
        if ("".equals(startCreateTime) || "".equals(endCreateTime)){
            log.error("时间为空："+startCreateTime);
        }
        Map paramsMap = new HashMap();
        paramsMap.put("startCreateTime",startCreateTime);
        paramsMap.put("endCreateTime",endCreateTime);
        String title = "物料列表";
        ExportParams params = new ExportParams(title, "物料数据", ExcelType.HSSF);
        List<ProductDto> productDtoList = productService.findAllProduct(paramsMap);
        Workbook workbook = ExcelExportUtil.exportExcel(params, ProductDto.class, productDtoList);
        ServletOutputStream out = null;
        try {
            response.setHeader("content-type", "application/octet-stream");
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(title + ".xls", "UTF-8"));
            out = response.getOutputStream();
            workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
            log.info("导出失败，失败原因："+e.getMessage());
        } finally {
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }*/

    @GetMapping("/getProductTypeByType")
    public JsonResult getProductTypeByType(@RequestParam Integer type){
        JsonResult productTypeByType = platformClient.getProductTypeByType(type);
        return JsonResult.success(productTypeByType);
    }

    @GetMapping("/getProductCategoryByType")
    public JsonResult getProductCategoryByType(@RequestParam Integer type){
        JsonResult productCategoryByType = platformClient.getProductCategoryByType(type);
        return productCategoryByType;
    }

    @GetMapping("/getProductBrandByType")
    public JsonResult getProductBrandByType(@RequestParam Integer type){
        JsonResult productBrandByType = platformClient.getProductBrandByType(type);
        return productBrandByType;
    }

    @GetMapping("/getProductUnitByType")
    public JsonResult getProductUnitByType(@RequestParam Integer type){
        JsonResult productBrandByType = platformClient.getProductUnitByType(type);
        return productBrandByType;
    }
    @GetMapping("/getProductSpecByProductTypeId")
    public JsonResult getProductSpecByProductTypeId(@RequestParam Long productTypeId){
        JsonResult productBrandByType = platformClient.getProductSpecByProductTypeId(productTypeId);
        return productBrandByType;
    }

    @GetMapping("/getProductAttrByProductTypeId")
    public JsonResult getProductAttrByProductTypeId(@RequestParam Long productTypeId){
        JsonResult productAttrByProductType = platformClient.getProductAttrByProductTypeId(productTypeId);
        return productAttrByProductType;
    }

    /**
     * 下载产品数据录入excel模板（简版）
     */
    @ApiOperation(value = "下载产品数据录入excel模板（简版）")
    @GetMapping("/compactTemplate")
    public void compactTemplate(HttpServletResponse response, HttpServletRequest request) throws IOException {
//        String[] headerArr = {"物料名称(*)","物料编号(*)","物料分类(*)","物料类型(*)","品牌(*)","市场价(*)","使用寿命","寿命单位","规格码(*)","单位(*)","安全库存数"};
        String[] headerArr = {"规格系列(*)","物料名称(*)","物料编号(*)","品牌(*)","市场价(*)","基础单位数量(*)","使用寿命","寿命单位","规格码","告警库存数量"};
        List<String[]> downData = new ArrayList<>();
        List<String> indexArr = new ArrayList<>();
        StringBuffer tempStr = new StringBuffer();
        // 规格系列
        Map<String, Object> params = new HashMap<>();
        params.put("categoryType", ProductCategory.CategoryType.purchase.getValue());
        List<ProductVO> productList = productService.list4app(params);
        if(CollectionUtil.isNotEmpty(productList)){
            for (ProductVO product : productList) {
                tempStr.append(product.getSpecCode()).append(",");
            }
            tempStr.delete(tempStr.length()-1, tempStr.length());
            downData.add(tempStr.toString().split(","));
            tempStr.delete(0,tempStr.length());
            indexArr.add("0");
        }

        //产品类型
        /*QueryWrapper<ProductTypeSelf> productTypeSelfQueryQrapper = new QueryWrapper<ProductTypeSelf>();
        productTypeSelfQueryQrapper.eq("type", ProductSelf.Type.knife);
        productTypeSelfQueryQrapper.eq("data_source_type", ProductTypeSelf.DataSourceType.enterprise);
        List<ProductTypeSelf> productTypeSelfList = productTypeSelfService.list(productTypeSelfQueryQrapper);
        if(CollectionUtil.isNotEmpty(productTypeSelfList)){
            for (ProductTypeSelf productTypeSelf : productTypeSelfList) {
                tempStr.append(productTypeSelf.getName()).append(",");
            }
            tempStr.delete(tempStr.length()-1, tempStr.length());
            downData.add(tempStr.toString().split(","));
            tempStr.delete(0,tempStr.length());
            indexArr.add("3");
        }*/
        //产品分类
        /*QueryWrapper<ProductCategorySelf> productCategorySelfQueryQrapper = new QueryWrapper<ProductCategorySelf>();
        productCategorySelfQueryQrapper.eq("type", ProductSelf.Type.knife);
        productCategorySelfQueryQrapper.eq("data_source_type", ProductCategorySelf.DataSourceType.enterprise);
        List<ProductCategorySelf> productCategorySelfList = productCategorySelfService.list(productCategorySelfQueryQrapper);
        if(CollectionUtil.isNotEmpty(productCategorySelfList)){
            for (ProductCategorySelf productCategorySelf : productCategorySelfList) {
                tempStr.append(productCategorySelf.getName()).append(",");
            }
            tempStr.delete(tempStr.length()-1, tempStr.length());
            downData.add(tempStr.toString().split(","));
            tempStr.delete(0,tempStr.length());
            indexArr.add("2");
        }*/
        //品牌
        QueryWrapper<ProductBrandSelf> productBrandSelfQueryQrapper = new QueryWrapper<ProductBrandSelf>();
        productBrandSelfQueryQrapper.eq("type", ProductSelf.Type.knife);
        productBrandSelfQueryQrapper.eq("data_source_type", ProductBrandSelf.DataSourceType.enterprise);
        List<ProductBrandSelf> productBrandSelfList = productBrandSelfService.list(productBrandSelfQueryQrapper);
        if(CollectionUtil.isNotEmpty(productBrandSelfList)){
            for (ProductBrandSelf productBrandSelf : productBrandSelfList) {
                tempStr.append(productBrandSelf.getName()).append(",");
            }
            tempStr.delete(tempStr.length()-1, tempStr.length());
            downData.add(tempStr.toString().split(","));
            tempStr.delete(0,tempStr.length());
//            indexArr.add("4");
            indexArr.add("3");
        }
        //单位
        /*QueryWrapper<ProductUnitSelf> productUnitInfoQueryQrapper = new QueryWrapper<ProductUnitSelf>();
        productUnitInfoQueryQrapper.eq("type", ProductSelf.Type.knife);
        productUnitInfoQueryQrapper.eq("data_source_type", ProductUnitSelf.DataSourceType.enterprise);
        List<ProductUnitSelf> productUnitInfoList = productUnitSelfService.list(productUnitInfoQueryQrapper);
        List<String> newList = productUnitInfoList.stream().map(ProductUnitSelf::getName).distinct().collect(Collectors.toList());
        if(CollectionUtil.isNotEmpty(newList)){
            for (String name : newList) {
                tempStr.append(name).append(",");
            }
            tempStr.delete(tempStr.length()-1, tempStr.length());
            downData.add(tempStr.toString().split(","));
            tempStr.delete(0,tempStr.length());
//            indexArr.add("9");
            indexArr.add("8");
        }*/
        //寿命单位
        for (ProductDetail.LifeUnit lifeUnitMethod : ProductDetail.LifeUnit.values()) {
            tempStr.append(lifeUnitMethod.getDesc()).append(",");
        }
        tempStr.delete(tempStr.length()-1, tempStr.length());
        downData.add(tempStr.toString().split(","));
        tempStr.delete(0,tempStr.length());
//        indexArr.add("7");
        indexArr.add("7");
        DownExcelUtil.createExcelTemplate(response, request, "产品导入模板(简版)", Arrays.asList(headerArr), downData, indexArr);
    }

    /**
     * 简版导入excel
     */
    @ApiOperation(value = "简版导入excel")
    @PostMapping("/compactImportExcel")
    public JsonResult compactImportExcel(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        int success = 0;  ///成功数（总数-失败数）
        if (file.isEmpty()) {
            return JsonResult.fail("上传文件为空！");
        }
        try {
            //获取原始的文件名
            ExcelUtil<CompactProductExcelIn> reader = new ExcelUtil<>();
            InputStream is = file.getInputStream();
            List<CompactProductExcelIn> list = reader.read(is, CompactProductExcelIn.class);
            success = list.size();
            if (CollectionUtils.isEmpty(list)) {
                return JsonResult.fail("请在表格中添加数据！");
            }
            int i = 1;
            List<ProductDetail> productDetailList = new ArrayList<>();
            //遍历Excel表每一行的数据
            for (CompactProductExcelIn u : list) {
                i++;
                String productName = u.getProductName().trim();
                if(StringUtils.isBlank(productName)){
                    return JsonResult.fail(300, "第"+i+"行产品系列未输入数据");
                }else if(StringUtils.isBlank(u.getSkuCode())){
                    return JsonResult.fail(300, "第"+i+"行物料编号未输入数据");
                }else if(StringUtils.isBlank(u.getBrand())){
                    return JsonResult.fail(300, "第"+i+"行品牌未输入数据");
                }else if(u.getMarketPrice() == null){
                    return JsonResult.fail(300, "第"+i+"行市场价未输入数据");
                }else if(u.getBaseQuantity() == null){
                    return JsonResult.fail(300, "第"+i+"行基础单位数量未输入数据");
                }

                ProductDetail productDetail = new ProductDetail();
                // 通过产品系列编号查询产品系列数据
                List<Product> productList = productService.list(new QueryWrapper<Product>().eq("spec_code", productName));
                if(productList.size() > 0){
                    productDetail.setProductId(productList.get(0).getId());
                }else{
                    return JsonResult.fail(300, "第"+i+"行产品系列数据不存在");
                }
                if(StringUtils.isBlank(u.getName())){
                    productDetail.setSkuName(productList.get(0).getName());
                }else{
                    productDetail.setSkuName(u.getName().trim());
                }
                String skuCode = u.getSkuCode().trim();
                QueryWrapper<ProductBrandSelf> brandSelfQueryQrapper = new QueryWrapper<ProductBrandSelf>();
                brandSelfQueryQrapper.eq("type", ProductSelf.Type.knife);
                brandSelfQueryQrapper.eq("name", u.getBrand().trim());
                brandSelfQueryQrapper.eq("data_source_type", ProductBrandSelf.DataSourceType.enterprise);
                List<ProductBrandSelf> brandSelfList = productBrandSelfService.getBaseMapper().selectList(brandSelfQueryQrapper);
                if(brandSelfList.size()>0){
                    productDetail.setBrandId(brandSelfList.get(0).getId());
                }else {
                    ProductBrandSelf productBrand = new ProductBrandSelf();
                    productBrand.setCode("JB-"+random());
                    productBrand.setName(u.getBrand().trim());
                    productBrand.setIsDeleted(true);
                    productBrandSelfService.save(productBrand);
                    productDetail.setBrandId(productBrand.getId());
                }
                productDetail.setSkuCode(skuCode);
                productDetail.setMarketPrice(u.getMarketPrice());
                productDetail.setBaseQuantity(u.getBaseQuantity());
                // 计算基础单价
                productDetail.setBasePrice(u.getMarketPrice().divide(new BigDecimal(u.getBaseQuantity().toString()), 2, RoundingMode.HALF_UP));
                productDetail.setSettledCompanyId(Long.valueOf(dynamicService.getEnterpriseId()));
                if(u.getLifeSpan()!=null){
                    productDetail.setLifeSpan(u.getLifeSpan());
                }
                if(StringUtils.isNotBlank(u.getSkuSpecValueNames())){
                    productDetail.setSkuSpecValueNames(u.getSkuSpecValueNames().trim());
                }else{
                    productDetail.setSkuSpecValueNames(productName);
                }
                if(StringUtils.isNotBlank(u.getLifeUnit())){
                    if(u.getLifeUnit().trim().equals(ProductDetail.LifeUnit.minute.getDesc())){
                        productDetail.setLifeUnit(ProductDetail.LifeUnit.minute);
                    }else if(u.getLifeUnit().trim().equals(ProductDetail.LifeUnit.number.getDesc())){
                        productDetail.setLifeUnit(ProductDetail.LifeUnit.number);
                    }
                }
                if(StringUtils.isNotBlank(u.getWarningQuantity())){
                    productDetail.setWarningQuantity(Integer.valueOf(u.getWarningQuantity().trim()));
                }
                productDetailList.add(productDetail);
            }
            productService.batchAddCompactProductDetail(productDetailList);
            return JsonResult.success("导入成功，成功"+success+"条！");
        } catch (Exception e) {
            log.error("简版导入上传文件异常！异常信息:", e);
            return JsonResult.exception("简版导入上传文件异常！异常信息:" + e.getMessage());
        }

    }

    private int random(){
        StringBuilder str=new StringBuilder();//定义变长字符串
        Random random=new Random();
        //随机生成数字，并添加到字符串
        for(int i=0;i<8;i++){
            str.append(random.nextInt(10));
        }
        //将字符串转换为数字并输出
        int num = Integer.parseInt(str.toString());
        return num;
    }

}
